package com.gzedu.common.exception;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class MyExceptionResolver implements HandlerExceptionResolver{

	/**
	 * 系统抛出的异常
	 */
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		// handler就是处理器适配器要执行Handler对象（只有一个method）
		//解析出异常类型
		//如果该异常类型是系统自定义的异常，直接取出异常信息，在错误页面展示
//		String message = null;
//		if(ex instanceof CustomException){
//			message = ((CustomException)ex).getMessage();
//		}else{//如果该异常类型不是系统自定义的异常，构造一个自定义的异常类型（信息为“未知错误”）
//			message = "未知错误";
//		}
		
		//上边的代码变为
		MyException myException = null;
		if(ex instanceof UnknownAccountException){
			myException = new MyException("用户不存在");
		}else if(ex instanceof IncorrectCredentialsException){
			myException = new MyException("密码不匹配");
		}else if(ex instanceof LockedAccountException){
			myException = new MyException("该帐号已被冻结");
		}else if(ex instanceof AuthenticationException){
			myException = new MyException("您无权执行该功能");
		}else if(ex instanceof MyException){
			myException = (MyException) ex;
		}else{//如果该异常类型不是系统自定义的异常，构造一个自定义的异常类型（信息为“未知错误”）
			myException = new MyException("未知错误");
			ex.printStackTrace();
		}
		//错误信息
		String message = myException.getMessage();
		
		//指向错误页面
		if(ex instanceof UnknownAccountException || ex instanceof IncorrectCredentialsException
				|| ex instanceof LockedAccountException || ex instanceof AuthenticationException){
			//定义modelAndView
			ModelAndView modelAndView = new ModelAndView("redirect:/login/toLogin");
			//将错误信息传到页面
			
			modelAndView.addObject("message",message);
			
			return modelAndView;
		}else{
			//定义modelAndView
			ModelAndView modelAndView = new ModelAndView();
			//将错误信息传到页面
			modelAndView.addObject("message",message);
			modelAndView.setViewName("/views/error/500");
			return modelAndView;
		}
		
	}

}
